import React, {useRef, useState, useEffect} from "react";
import './Color.less'

function createGradient (cb) {
  const colors = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5].map(index => 255 / 6 * index);
  return colors.map((clr) => {
    const color = clr > 0 ? 255 - clr : 255;
    const otherColor = clr > 0 ? 0 : Math.abs(clr);

    return cb(color, otherColor)
  })
}

function Preset({ data, index }) {
  if (Array.isArray(data)) {
    return data.map((item, index) => <Preset data={item} index={index} key={index} />)
  } else {
    const {r, g, b } = data;
      return (
        <div
          key={index}
          className={`color-preset color-preset-0${index}`}
          style={{ backgroundColor: `rgb(${r}, ${g}, ${b})` }}
        />
      )
  }
}

/**
 *
 * @param pixel: [r, g, b, a] = ctx.getImageData(x, y, 1, 1).data;
 */
function getPixelColor ([r, g, b, a] = []) {
  a = Math.round(a / 255 * 100) / 100;

  var rHex = r.toString(16);
  r < 16 && (rHex = "0" + rHex);

  var gHex = g.toString(16);
  g < 16 && (gHex = "0" + gHex);

  var bHex = b.toString(16);
  b < 16 && (bHex = "0" + bHex);

  return {
    rgba: "rgba(" + r + "," + g + "," + b + "," + a + ")",
    rgb: "rgb(" + r + "," + g + "," + b + ")",
    hex: "#" + rHex + gHex + bHex,
    r: r,
    g: g,
    b: b,
    a: a
  };
}

function Collapse({ title, children }) {
  return (
    <div className="color-selector-collapse">
      <div className="color-selector-collapse-header">
        <span>{title}</span>
        <span>＞</span>
      </div>
      {children}
    </div>
  )
}

function Popover({ title, children, type }) {
  return (
    <div className={`color-selector-modal color-selector${type}-modal`}>
      <div className="selector-direction selector-direction-right"/>
      <div className="color-selector-header">{ title }</div>
      <div className={`modal-body color-selector-${type}`}>
        { children }
      </div>
    </div>
  )
}

function ColorPicker({ defaultValue = '#fff', onChange }) {
  const [color, setColor] = useState(defaultValue)
  const [selectorShaders, setSelectorShaders] = useState<boolean>(false)
  const canvasRef = useRef()
  let ref = useRef();
  const datas = [
    createGradient((color, o) => ({r: color, g: o, b: o })),
    createGradient((color, o) => ({r: color, g: color, b: o })),
    createGradient((color, o) => ({r: o, g: color, b: o })),
    createGradient((color, o) => ({r: o, g: color, b: color })),
    createGradient((color, o) => ({r: o, g: o, b: color })),
    createGradient((color, o) => ({r: color, g: o, b: color })),
  ]

  useEffect(() => {
    if (!canvasRef?.current) return;
    const $canvas = canvasRef.current
    const ctx = $canvas.getContext('2d', { willReadFrequently: true });

    ctx.clearRect(0, 0, $canvas.width, $canvas.height);
    ref.current = ctx

    var hGrad = ctx.createLinearGradient(0, 0, $canvas.width, 0);
    hGrad.addColorStop(0 / 6, '#F00');
    hGrad.addColorStop(1 / 6, '#FF0');
    hGrad.addColorStop(2 / 6, '#0F0');
    hGrad.addColorStop(3 / 6, '#0FF');
    hGrad.addColorStop(4 / 6, '#00F');
    hGrad.addColorStop(5 / 6, '#F0F');
    hGrad.addColorStop(6 / 6, '#F00');

    hGrad.addColorStop(6 / 6, 'rgb(0, 100, 100)');

    // 673ab7
    ctx.fillStyle = hGrad;
    ctx.fillRect(0, 0, $canvas.width, $canvas.height);

    var vGrad = ctx.createLinearGradient(0, 0, 0, $canvas.height);
    switch ('s') {
      case 's': // 从纯色到纯白色
        vGrad.addColorStop(0, 'rgba(255,255,255,0)');
        vGrad.addColorStop(1, 'rgba(255,255,255,1)');
        break;
      case 'v': // 从纯色到纯黑色
        vGrad.addColorStop(0, 'rgba(0,0,0,0)');
        vGrad.addColorStop(1, 'rgba(0,0,0,1)');
        break;
    }
    ctx.fillStyle = vGrad;
    ctx.fillRect(0, 0, $canvas.width, $canvas.height);
  }, [canvasRef] as any)

  const onClick = (ev) => {
    const ctx = ref.current;
    const { offsetX, offsetY } = ev.nativeEvent;
    const [r, g, b, a] = ctx.getImageData(offsetX, offsetY, 1, 1).data
    setColor(`rgba(${r}, ${g}, ${b}, ${a})`)
  }

  const onCollapse = () => {

  }

  const onColorChange = () => {

  }

  const onColorBarClick = () => {
    setSelectorShaders(true)
  }


  return (
    <div className="col-16 form-item-control color-selector">
      <input
        className="color-selector-input"
        defaultValue={defaultValue}
        onChange={onChange}
      />
      <div
        className="color-selector-bar"
        style={{backgroundColor: defaultValue}}
        onClick={onColorBarClick}
      >
        {
          selectorShaders && (
            <div className="color-selector-model color-selector-shaders-model">
              <div className="selector-direction selector-direction-right-top"/>
              <div className="color-selector-header">颜色选择</div>
              <div className="modal-body">
                <canvas
                  ref={canvasRef}
                  className="color-selector-canvas"
                  onClick={onClick}
                />
              </div>
              <div className="color-selector-collapse">
                <div className="color-selector-collapse-header">
                  <span>#{color}</span>
                </div>
              </div>

              <Collapse title="预设" onClick={onCollapse}>
                <Popover title="预设" type="preset">
                  <Preset data={datas} onClick={onColorChange}/>
                </Popover>
              </Collapse>

              <Collapse title="常用" onClick={onCollapse}>
                <Popover title="常用" type="commonly">
                  <Preset data={datas} onClick={onColorChange}/>
                </Popover>
              </Collapse>
            </div>
          )
        }
      </div>
    </div>
  )
}

export default React.memo(({ label, filed, style = {}, margin, padding, border, onChange }) => {
  const hasEyeDrop = 'EyeDropper' in window;
  const __onChange = (ev) => {
    console.log('__onChange:color => ', ev.target.value)
    onChange && onChange(ev.target.value, `style.${filed}`)
  }
  console.log('__onChange', hasEyeDrop)

  return (
    <div className="form-item row flex-center">
      <div className="col-8 form-item-label">
        <label>{ label }</label>
      </div>
      {
        hasEyeDrop ? (
          <ColorPicker defaultValue={`style.${filed}`} onChange={__onChange}/>
        ) : (
          <div className="col-16 form-item-control color-selector">
            <input
              type="color"
              className="color-selector-input"
              defaultValue={ style[filed] }
              onChange={__onChange}
            />
          </div>
        )
      }
    </div>
  )
})